//-----------------------------------------------------------------------
// <copyright file="imageshelper.cs" company="Microsoft">
//     (c) 2009 Microsoft corp.
//     This software is distributed under Microsoft Public License (MSPL)
//     see http://opensource.org/licenses/ms-pl.html
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Security;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.UI;
using System.Xml;
using System.Xml.Linq;

using AjaxControlToolkit;

using LiveSearchApiPowerToys.Components;
using LiveSearchApiPowerToys.Components.net.live.search.api;

/// <summary>
/// fetches from Live Search batches of images to serve to a control of type ImageSearchSlideShow
/// </summary>
[WebService(Namespace = "http://LiveSearchApiPowerToys.com/services")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class ImagesHelper : System.Web.Services.WebService
{
    /// <summary>
    /// The Live Search AppID (get yours from http://search.live.com/developers )
    /// </summary>
    private string liveSearchAppId = string.Empty;

    /// <summary>
    /// Initializes a new instance of the ImagesHelper class
    /// </summary>
    public ImagesHelper()
    {
        this.liveSearchAppId = System.Configuration.ConfigurationManager.AppSettings["LiveSearch20AppKey"];
    }

    /// <summary>
    /// returns an array of images from the Live Search Image Index into a slide array 
    /// </summary>
    /// <param name="contextKey">serialized JSON query</param>
    /// <returns>an array of Slide ready for displaying</returns>
    [WebMethod]
    public AjaxControlToolkit.Slide[] SearchPhotoEx(string contextKey)
    {
        // Right now context key is the search query
        AjaxControlToolkit.Slide[] slides = null;

        if (!string.IsNullOrEmpty(contextKey))
        {
            // Deserialize the ImageQuery from the passed parameter
            ImageQuery myImgQuery = ImageQuery.CreateImageQueryFromJson(contextKey);
            if (myImgQuery != null)
            {
                // Check if the query pattern has been provided
                if (myImgQuery.CacheIdentifier != Guid.Empty)
                {
                    // if so create the cache identifier
                    string cacheIdentifier = "QP_IMG_" + myImgQuery.CacheIdentifier;

                    // check if the cached value is available
                    if (this.Context.Cache[cacheIdentifier] != null)
                    {
                        // return the cached object - no need to call Live Search
                        return (AjaxControlToolkit.Slide[])this.Context.Cache[cacheIdentifier];
                    }
                }

                // get images from Live search
                ImageResult[] images = myImgQuery.ExecuteQuery(this.liveSearchAppId);

                // if images have been found create Ajax Slide Show slides and cache them
                if (images.Length > 0)
                {
                    slides = new Slide[images.Length];
                    for (int i = 0; i < images.Length; i++)
                    {
                        slides[i] = new Slide(images[i].MediaUrl, images[i].Title, new Uri(images[i].MediaUrl).Host);
                    }

                    // Check if the query pattern has been provided
                    if (myImgQuery.CacheIdentifier != Guid.Empty)
                    {
                        // if so create the cache identifier and check the cached value if available
                        string cacheIdentifier = "QP_IMG_" + myImgQuery.CacheIdentifier;
                        this.Context.Cache.Add(
                                            cacheIdentifier,
                                            slides,
                                            null,
                                            System.Web.Caching.Cache.NoAbsoluteExpiration,
                                            myImgQuery.CacheExpirationInterval,
                                            System.Web.Caching.CacheItemPriority.Default,
                                            null);
                    }
                }
            }
        }
        else
        {
            // An exception occurred while accessing the network.
            Trace.TraceError("ImagesHelper Service - SearchPhotos", "Image query is empty!");
        }

        return (slides);
    }
}

